import router, { asyncRoutes } from './router'
import store from './store'
// import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
// import { getToken } from '@/utils/auth' // get token from cookie
// import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  if (store.state.user.token) {
    if (to.path === '/login') {
      next('/')
    } else {
      // console.log(1)log
      // console.log(store.state.user)
      // console.log(store.state.user.userInfo)
      // 如果没有id就去获取
      if (!store.getters.userifoid) {
        // await store.dispatch('user/getuserAPI')
        // console.log(666666666666)
        // 接收user模块传过来的 return res.data.roles.menus
        const roles = await store.dispatch('user/getuserAPI')
        console.log(roles)
        // 定义一个空数组接收过滤完和传过来的name一样的路由名
        let list = []
        list = asyncRoutes.filter(item => {
          // console.log(item.children[0].name)
          return roles.includes(item.children[0].name)
        })
        // console.log(list)
        // console.log(roles)
        // 把过滤完的数组存在vuex
        store.commit('menu/setMenuList', list)
        router.addRoutes([...list, { path: '*', redirect: '/404', hidden: true }]) // 改写成动态添加方法
        next({
          ...to, // next({ ...to })的目的,是保证路由添加完了再进入页面 (可以理解为重进一次)
          replace: true // 重进一次, 不保留重复历史
        })
      }
      next()
      // console.log(2)
      // 解决刷新出现的白屏bug
    }
  } else {
    if (whiteList.indexOf(to.path) > -1) {
      next()
    } else {
      next('/login')
    }
  }
  NProgress.done()
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
